import {
  voteList
} from '../../apis/vote';
import {
  splicing,
  formatTime
} from '../../utils/util';
const app = getApp();

Page({
  data: {
    voteList: [],
    pageNum: 1,
    isRequest: false,
    isHaveMore: true
  },

  onLoad() {
    this.getVoteList(1);
  },

  onShareAppMessage() {
    return {
      title: '北京市移民及出入境服务行业协会',
      path: '/pages/start/index',
      imageUrl: '/images/logo.png'
    }
  },

  // 页面触底加载
  onReachBottom() {
    if (this.data.isHaveMore && !this.data.isRequest) {
      this.getVoteList(this.data.pageNum + 1, 'load');
    };
  },
  // 页面下拉刷新
  onPullDownRefresh(e) {
    this.setData({
      pageNum: 1,
      isHaveMore: true
    });
    this.getVoteList(1);
  },

  // 获取投票列表
  getVoteList(pageNum, type) {
    if (this.data.isRequest) return
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    this.setData({
      isRequest: true
    });
    voteList(pageNum, 10).then(res => {
      wx.stopPullDownRefresh();
      wx.hideLoading();
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        this.setData({
          pageNum: pageNum
        });
        let {
          rows,
          total
        } = res.data;
        rows.forEach(v => {
          v.image = splicing(v.image);
          v.timeEnd = formatTime(v.timeEnd);
        });
        if (type === 'load') {
          rows.forEach(v => {
            this.data.voteList.push(v);
          });
          this.setData({
            voteList: this.data.voteList
          });
        } else {
          this.setData({
            voteList: rows
          });
        };
        if (this.data.voteList.length === total) {
          this.setData({
            isHaveMore: false
          });
        };
      };
    });
  },

  // 投票详情
  voteDetails(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/voteDetails/index?voteId=${id}`
    });
  }
})